<?php

namespace apps\marriage\app\mp\controller;

use apps\marriage\core\logic\CaptchaLogic;
use apps\marriage\core\service\MemberProfileService;
use apps\marriage\core\service\VipCardNoService;
use apps\marriage\core\service\VipCardService;
use think\Exception;
use think\Request;

class VipCardController extends BaseMarriageMpController
{
    /**
     * @var VipCardService
     */
    private $vipCardService;

    /**
     * @var VipCardNoService
     */
    private $vipCardNoService;

    /**
     * @var CaptchaLogic
     */
    private $captchaLogic;

    /**
     * @var MemberProfileService
     */
    private $memberProfileService;

    protected function init()
    {
        parent::init();
        $this->vipCardService = service('VipCard', SERVICE_NAMESPACE);
        $this->vipCardNoService = service('VipCardNo', SERVICE_NAMESPACE);
        $this->captchaLogic = logic('Captcha', LOGIC_NAMESPACE);
        $this->memberProfileService = service('MemberProfile', SERVICE_NAMESPACE);
    }

    public function preview(Request  $request)
    {
        $no = $request->param('no', '');
        $vipCardNo = $this->vipCardNoService->info(['no' => $no]);
        if(empty($vipCardNo)) {
            throw new Exception('卡号无效');
        }
        $vipCard = $this->vipCardService->getByPk($vipCardNo['vip_card_id']);
        $vipCard = $this->vipCardService->format($vipCard);
        return $this->success(['card' => $vipCard]);
    }

    public function active(Request  $request)
    {
        $captcha = $request->param('captcha');
        $sessionId = $request->param('session_id');
        $no = $request->param('no', '');

        if(!$this->captchaLogic->verify($sessionId, $captcha)) {
            throw new Exception('验证码错误');
        }

        $this->vipCardNoService->onActive($this->user['id'], $no);

        $member = $this->memberProfileService->getByUserId($this->user['id']);
        $member = $this->memberProfileService->format($member);

        return $this->success(['member' => $member]);
    }
}